package com.smartstate.iot.service;

import cn.hutool.core.date.DateTime;
import com.alibaba.fastjson.JSON;
import com.smartstate.iot.config.SpringBeanUtils;
import com.smartstate.iot.config.redis.RedisService;
import com.smartstate.iot.config.web.SpringUtils;
import com.smartstate.iot.mqtt.client.MyMQTTClient;
import com.smartstate.iot.mqtt.common.GlobalMqttParam;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttException;

import java.util.*;

@Slf4j
public class PointsAwardedThreadService implements Runnable {

    GlobalMqttParam globalMqttParam = SpringUtils.getBean(GlobalMqttParam.class);
    String broker = globalMqttParam.getBroker();
    String userName = globalMqttParam.getUserName();
    String passWord = globalMqttParam.getPassWord();
    String clientId1 = globalMqttParam.getSubClientId1() + new DateTime();
    int keepalive = globalMqttParam.getKeepalive();
    int timeout = globalMqttParam.getTimeout();
    MyMQTTClient myMQTTClient = new MyMQTTClient(broker, userName, passWord, clientId1, keepalive, timeout);

    String topic;
    String msg;

    public PointsAwardedThreadService(String topic, String msg) {
        this.topic = topic;
        this.msg = msg;
    }

    @Override
    public void run() {
        Map<String,Object> map = JSON.parseObject(msg, Map.class);
        String id = (String) map.get("id");
        List writeParameters = (List) map.get("WriteParameters");
        String ip = getIp(id);
        HashMap<String, Object> msgMap = new HashMap<>();
        msgMap.put("id",ip);
        msgMap.put("writeParameters",writeParameters);
        try {
            myMQTTClient.connect();
            myMQTTClient.publish(JSON.toJSONString(msgMap),"SH/NJ/HK/CONFIG");
        } catch (MqttException e) {
            e.printStackTrace();
        }
        log.info("转发配置成功！");
    }

    private String getIp(String id) {
        RedisService redisService = SpringBeanUtils.getBean(RedisService.class);
        Map<String, Object> cacheMap = redisService.getCacheMap(id);
        System.out.println(cacheMap.get("ip").toString());
        String ip = cacheMap.get("ip").toString();
        return ip;
    }
}
